package com.jewaton.auth.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jewaton.auth.entity.User;
import com.jewaton.auth.entity.UserLoginList;
import com.jewaton.auth.service.UserLoginListService;
import com.jewaton.auth.tools.Common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;

/**
* 登录成功后执行
*/
public class CustomAuthenticationSuccessHandler extends
		SavedRequestAwareAuthenticationSuccessHandler {
    private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationSuccessHandler.class);

	@SuppressWarnings("unused")
	private RequestCache requestCache = new HttpSessionRequestCache();

    @Autowired
    private UserLoginListService userLoginListService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws ServletException, IOException {

        try {
            //从spring上下文中取出用户
            User user = (User) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();

            UserLoginList userLoginList = new UserLoginList();
            userLoginList.setUserId(user.getUserId());
            userLoginList.setLoginIp(Common.toIpAddr(request));
            userLoginListService.add(userLoginList);
        }catch (Exception e){
            logger.error(e.toString(),e);
            throw e;
        }

		super.onAuthenticationSuccess(request, response, authentication);
	}
}
